package com.grape.session.impl;

import com.grape.session.ISessionStore;
import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;

@Component
public class ChannelGroupSessionStoreImpl implements ISessionStore {

    private static final ChannelGroup CHANNEL_GROUP = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    private static final ConcurrentHashMap<String, ChannelId> CHANNEL_MAP = new ConcurrentHashMap<>();

    /**
     * 获取channelGroup
     * @return  管道组
     */
    @Override
    public ChannelGroup channelGroup() {
        return CHANNEL_GROUP;
    }

    /**
     * 添加channel
     * @param channel   成功连接后的通道
     */
    @Override
    public void addChannel(Channel channel) {
        CHANNEL_GROUP.add(channel);
        CHANNEL_MAP.put(channel.id().asLongText(), channel.id());
    }

    /**
     * 移除channel
     * @param channel   成功连接后的通道
     */
    @Override
    public void removeChannel(Channel channel) {
        CHANNEL_GROUP.remove(channel);
        CHANNEL_MAP.remove(channel.id().asLongText());

    }

    /**
     * 根据id查找channel
     * @param id    用户id
     * @return      成功连接后的通道
     */
    @Override
    public Channel findChannel(String id) {
        return CHANNEL_GROUP.find(CHANNEL_MAP.get(id));
    }
}
